<script setup lang="tsx">
import qs from 'qs'
import type { FormInstance } from 'element-plus'
import { ElButton,
  ElMessage,
} from 'element-plus'
import useClipboard from 'vue-clipboard3'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/hexiao'
import { GetOptionData } from '@/api/modules/subscriber'
import { GetJingdianData } from '@/api/modules/homePage'
import detailStore from '@/store/modules/cacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const id = route.query.id as string

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  openId: '',
  mobile: '',
  enable: true,
  jingDianShopName: '',
  id: id || 0,
})
const findFrom = ref({
  UserId: '',
  SCOpenId: '',
  UserPhone: '',
  UserNickName: '',
})
const OpenIdOptionList = ref([])

interface JingdianListType {
  id: number
  shopName: string
}
const JingdianList = ref<JingdianListType[]>([])
// 提交
async function SubmitData() {
  if (id) {
    // 编辑
    PutModifyData(ruleForm.value).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'userList' })
      }
    })
  }
  else {
    // 添加
    PostCreateData(ruleForm.value).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.EmptyHexiao()
        router.push({ name: 'userList' })
      }
    })
  }
}

watch(ruleForm, (newValue) => {
  if (!id) {
    detailData.RememberHexiao(newValue)
  }
}, { deep: true })

const total = ref(0)
function GetOpenIdOptionList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.UserId && ({ UserIdList: [findFrom.value.UserId] })),
    ...(findFrom.value.SCOpenId && ({ SCOpenId: findFrom.value.SCOpenId })),
    ...(findFrom.value.UserPhone && ({ UserPhone: findFrom.value.UserPhone })),
    ...(findFrom.value.UserNickName && ({ UserNickName: findFrom.value.UserNickName })),
  }
  const parameter = qs.stringify(params)
  GetOptionData(parameter).then((res: any) => {
    if (res.statusCode === 200) {
      OpenIdOptionList.value = res.data.items
      total.value = res.data.total
    }
    else {
      ElMessage.error(`获取数据失败。${res.errors}`)
    }
  })
}

function SetData(OpenId: string, UserPhone: string) {
  ruleForm.value.openId = OpenId
  ruleForm.value.mobile = UserPhone
}

async function copy(OpenId: string) {
  const clipboard = useClipboard()
  try {
    // 使用 navigator.clipboard.writeText 来复制文本
    // await navigator.clipboard.writeText(`pages/adPage/adPage?landing_id=${id}&pushCoupons=0`)
    await clipboard.toClipboard(OpenId)
    ElMessage.success('复制成功')
  }
  catch (error) {
    const textarea = document.createElement('textarea')
    textarea.value = OpenId
    document.body.appendChild(textarea)
    textarea.select()
    // 使用现代浏览器支持的复制命令
    const successful = document.execCommand('copy')
    if (!successful) {
      ElMessage.error('复制失败')
    }
    else {
      ElMessage.success('复制成功')
    }
    document.body.removeChild(textarea)
  }
}

// 翻页
let PageSize = 20
function handleSizeChange(val: number) {
  GetOpenIdOptionList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetOpenIdOptionList(val, PageSize)
}

function GetOpenIdData() {
  GetOpenIdOptionList()
}

onMounted(async () => {
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
      }
    })
  }
  else {
    ruleForm.value = detailData.GetHexiaoData()
  }
  const JingdianData: any = await GetJingdianData()
  if (JingdianData.statusCode === 200) {
    JingdianList.value = JingdianData.data.filter((item: any) => item.shopName !== '')
  }
  GetOpenIdOptionList()
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="OpenId">
              <!-- <el-select v-model="ruleForm.openId" placeholder="请选择" clearable>
                <el-option v-for="item in OpenIdOptionList" :key="item.userId" :label="item.userNickName" :value="item.scOpenId" />
              </el-select> -->
              <el-input v-model="ruleForm.openId" style="width: 300px;" placeholder="请输入OpenId" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="手机号">
              <el-input v-model="ruleForm.mobile" style="width: 300px;" placeholder="请输入手机号" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="景点店铺名称">
              <el-select v-model="ruleForm.jingDianShopName" placeholder="请选择景点店铺名称" style="width: 300px;">
                <el-option v-for="item in JingdianList" :key="item.id" :label="item.shopName" :value="item.shopName" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="是否启用">
              <el-switch
                v-model="ruleForm.enable"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain title="查询OpenId">
        <ElRow :gutter="20">
          <ElCol :md="5">
            <ElFormItem label="用户ID">
              <el-input v-model="findFrom.UserId" style="width: 300px;" placeholder="请输入用户ID" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="OpenId">
              <el-input v-model="findFrom.SCOpenId" style="width: 300px;" placeholder="请输入OpenId" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="微信昵称">
              <el-input v-model="findFrom.UserNickName" style="width: 300px;" placeholder="请输入微信昵称" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="5">
            <ElFormItem label="授权手机号">
              <el-input v-model="findFrom.UserPhone" style="width: 300px;" placeholder="请输入授权手机号" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="4">
            <ElFormItem label="操作">
              <ElButton @click="GetOpenIdData">
                查询
              </ElButton>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <el-table :data="OpenIdOptionList" stripe style="width: 100%;" border height="400">
              <el-table-column align="center" prop="userId" label="userId" width="150" />
              <el-table-column align="center" prop="scOpenId" label="OpenId" min-width="350" />
              <el-table-column align="center" prop="userNickName" label="微信昵称" width="300" />
              <el-table-column align="center" prop="userPhone" label="核销人手机号" width="200" />
              <el-table-column align="center" prop="address" label="操作" fixed="right" min-width="100">
                <template #default="scope">
                  <ElButton type="primary" @click="SetData(scope.row.scOpenId, scope.row.userPhone)">
                    应用
                  </ElButton>
                  <ElButton type="info" style="padding: 0 10px;" @click="copy(scope.row.scOpenId)">
                    复制OpenId
                  </ElButton>
                </template>
              </el-table-column>
            </el-table>
            <div style="height: 10px;" />
            <el-pagination
              :default-page-size="20"
              :page-sizes="[5, 10, 20, 50, 100]"
              layout="total, sizes, ->, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </elcol>
        </elrow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
